<template>
  <el-container>
    <el-drawer
      title="菜单树"
      :visible.sync="drawer"
      direction="btt"
      style="position: absolute"
      z-index="10"
      :modal="true"
      size="60%"
      @opened="handleOpened"
      :before-close="handleClose"
    >
      <el-button type="success" size="mini" round @click="saveMenu"
        >保存</el-button
      >
      <el-scrollbar
        ><el-tree
          style="height: 300px"
          ref="menuTree"
          :data="menuList"
          show-checkbox
          node-key="id"
          :default-checked-keys="roleMenuIds"
          :props="defaultProps"
        >
          <span slot-scope="{ data }">
            <Item :icon="data.icon" />
            <span style="margin-left: 10px">{{ data.title }}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </el-drawer>
    <el-dialog
      :title="isAdd ? '角色添加' : '角色编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="70%"
      height="60%"
      :close-on-click-modal="false"
      center
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        label-width="150px"
        fullscreenLoading
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="角色编号">
              <el-input
                v-model.trim="roleForm.id"
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input
                v-model="roleForm.name"
                placeholder="请输入名称"
                class="inputWdith"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="角色描述" prop="title">
              <el-input
                v-model="roleForm.description"
                placeholder="角色描述"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="24">
            <div style="text-align: center">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm('roleForm')"
                  v-loading.fullscreen.lock="fullscreenLoading"
                  >确认</el-button
                >
                <el-button @click="resetForm('roleForm')">重置</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增角色</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入角色名称"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="roleQueryParam.name"
          >
          </el-input>
          <el-select
            v-model="roleQueryParam.description"
            placeholder="角色类型"
            filterable
            clearable
            style="width: 20%; margin-left: 40px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.description"
              :value="item.description"
            ></el-option>
          </el-select>

          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="roleTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="roleList"
            fit
            @row-dblclick="handleRowDblclick"
            border
            max-height="700"
            size="medium "
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column prop="id" label="角色编号"> </el-table-column>
            <el-table-column prop="name" label="角色名称"> </el-table-column>
            <el-table-column prop="description" label="角色类型">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="total"
            hide-on-single-page
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle';
import {
  reqGetRoleList,
  reqEditRole,
  reqBatchAddRole,
} from '@/views/Custom/SystemSettingsMng/RoleMenuMng/api/RoleMng.js';
import {
  reqGetRoleMenuListByRoleId,
  reqEditByRowId,
} from '@/views/Custom/SystemSettingsMng/RoleMenuMng/api/RoleMenuMngApi.js';
import { mapGetters } from 'vuex';
import { reqQueryMenu } from '../MenuMng/api/MenuMngApi';
export default {
  name: 'RoleMenuMng',
  data() {
    return {
      prefixUrl: process.env.VUE_APP_BASE_API,
      isAdd: false,
      fullscreenLoading: false,
      loading: false,
      centerDialogVisible: false,
      condition: {},
      currentPage: 1,
      pageSize: 10,
      total: 0,
      roleList: [],
      roleMenuList: [],
      menuList: [],
      menuTree: [],
      roleForm: {},
      roleQueryParam: {},
      roleId: undefined,
      roleMenuIds: [],
      drawer: false,
      selectMenuTree: [],
      defaultProps: {
        children: 'children',
        label: 'title',
        id: 'id',
      },
    };
  },
  computed: {
    // roleMenuIds() {
    //   let checkedMenuIds = this.roleMenuList.map((item) => item.menuId);
    //   return checkedMenuIds;
    // },
  },
  watch: {
    menuTree() {
      this.$set(this, 'menuList', this.menuTree);
    },
  },
  mounted() {
    this.loading = true;

    // 获取角色列表
    this.getRoleList();
    // 获取菜单列表
    this.getMenuTree();
  },
  methods: {
    // 刷新角色列表
    refresh: throttle(async function () {
      this.loading = true;
      this.currentPage = 1;
      await this.getRoleList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    handleOpened() {
      this.selectMenuTree = this.$refs.menuTree.getCheckedKeys();
    },
    reset() {
      this.$nextTick(() => {
        this.$refs.menuTree.setCheckedKeys([]);
      });
    },

    // 抽屉关闭
    handleClose() {
      this.reset();
      this.drawer = false;
    },
    // 新增职位类别
    handleAdd() {
      this.roleForm = {};
      if (this.$refs.roleForm) {
        this.resetForm('roleForm');
      }
      this.isAdd = true;
      this.centerDialogVisible = true;
    },

    // 保存更新后的菜单
    saveMenu() {
      let childrenNodeIds = this.$refs.menuTree.getCheckedKeys();

      let parentNodeIds = this.$refs.menuTree.getHalfCheckedKeys();
      this.selectMenuTree = [...childrenNodeIds, ...parentNodeIds];

      // 发送请求
      reqEditByRowId(this.roleId, this.selectMenuTree).then((res) => {
        this.$message.success(res.message);
        this.drawer = false;
        this.reset();
      });
    },
    // 获取菜单列表
    getMenuTree() {
      // this.$store.dispatch('MenuMng/getMenuTree');
      reqQueryMenu().then((res) => {
        this.menuTree = res.data.menuTree || [];
      });
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserList();
    },

    // 查询角色菜单列表
    getRoleMenuList(rowId) {
      reqGetRoleMenuListByRoleId(rowId).then((res) => {
        this.roleMenuList = res.data.roleMenuListByRoleId;
        let parentMenuIds = this.menuTree
          .filter((item) => {
            return !item.hasOwnProperty('parentId');
          })
          .map((item) => item.id);
        // 去除父菜单
        let arr = [];
        this.roleMenuList = this.roleMenuList.forEach(function (m) {
          let flag = parentMenuIds.includes(m.menuId);
          if (!flag) {
            arr.push(m.menuId);
          }
        });
        // 只回显子菜单
        this.roleMenuIds = arr;
      });
    },

    // 行点击事件--显示角色对应的菜单
    handleRowDblclick(row) {
      this.roleId = row.id;
      this.getRoleMenuList(row.id);

      this.drawer = true;
    },
    // 重置表单判定状态
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 编辑角色
    handEdit(row) {
      if (this.$refs.roleForm) {
        this.resetForm('roleForm');
      }
      this.centerDialogVisible = true;
      this.roleForm = row;
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            if (this.isAdd) {
              let paramsArray = [];
              UserMng;
              let params = {
                ...this.roleForm,
              };
              paramsArray.push(params);

              // 发送请求
              reqBatchAddRole(paramsArray).then((res) => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 2 * 1000,
                });
                this.fullscreenLoading = false; // 关闭遮罩层
                this.isAdd = false; // 重置表单状态
                this.centerDialogVisible = false;
              });
            } else {
              reqEditRole(this.roleForm).then((res) => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 2 * 1000,
                });
                this.fullscreenLoading = false; // 关闭遮罩层
                this.isAdd = false; // 重置表单状态
                this.centerDialogVisible = false;
              });
            }
          } catch (error) {
            Message.error(error || 'Has Error');
          }
        } else {
          return false;
        }
      });
    },

    // 条件查询
    queryByCondition() {
      // 初始化条件查询参数
      this.condition = {
        ...this.roleQueryParam,
      };
      this.getRoleList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 查询角色列表
    getRoleList() {
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      reqGetRoleList(params).then((res) => {
        this.loading = false;
        this.roleList = res.data.roleIPage.records;
        this.currentPage = res.data.roleIPage.currentPage;
        this.pageSize = res.data.roleIPage.pageSize;
        this.total = res.data.roleIPage.total;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.block {
  text-align: center;
}
</style>
